<template>
  <s-layout>
  <!-- Using view instead of s-layout for broader compatibility, style similarly -->
  <view class="change-password-page">
    <view class="container">
      <!-- Header Section (similar to target) -->
      <view class="header-box">
        <text
          class="cicon-key"
          style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
        ></text>
        <text class="title">更改账号密码</text>
        <!-- Changed title -->
      </view>

      <!-- Form Card -->
      <view class="form-card">
        <fui-input
          label="原密码"
          placeholder="请输入原密码"
          v-model="passwords[0]"
          :password="showPassword[0]"
          maxlength="20"
          @blur="validatePasswordLength(0)"
        >
          <!-- Suffix Toggle Icon -->
          <fui-icon
            :name="showPassword[0] ? 'invisible' : 'visible'"
            color="#0052D9"
            :size="50"
            @click="togglePasswordVisibility(0)"
          ></fui-icon>
        </fui-input>

        <!-- New Password Input -->
        <fui-input
          label="新密码"
          placeholder="请输入6-20位新密码"
          v-model="passwords[1]"
          :password="showPassword[1]"
          maxlength="20"
          @blur="validatePasswordLength(1)"
        >
          <!-- Suffix Toggle Icon -->
          <fui-icon
            :name="showPassword[1] ? 'invisible' : 'visible'"
            color="#0052D9"
            :size="50"
            @click="togglePasswordVisibility(1)"
          ></fui-icon>
        </fui-input>

        <!-- Confirm New Password Input -->
        <fui-input
          label="确认新密码"
          placeholder="请再次输入新密码"
          v-model="passwords[2]"
          :password="showPassword[2]"
          maxlength="20"
          :borderBottom="false"
          @blur="validatePasswordLength(2)"
        >
          <!-- Suffix Toggle Icon -->
          <fui-icon
            :name="showPassword[2] ? 'invisible' : 'visible'"
            color="#0052D9"
            :size="50"
            @click="togglePasswordVisibility(2)"
          ></fui-icon>
        </fui-input>
      </view>

      <!-- Submit Button (similar to target) -->
      <view class="submit-btn" @click="handleSubmit">
        <text class="btn-text">确认更改</text>
        <!-- Changed button text -->
      </view>
    </view>
  </view>
</s-layout>
</template>

<script setup>
import { ref } from "vue";
import sheep from "@/sheep";
import other from "@/sheep/api/other";

// Assuming FirstUI components are globally registered or imported locally if needed
// import FuiSection from '@/components/firstui/fui-section/fui-section.vue';
// import FuiInput from '@/components/firstui/fui-input/fui-input.vue';
// import FuiIcon from '@/components/firstui/fui-icon/fui-icon.vue';

// --- Reactive Data ---
const passwords = ref(["", "", ""]); // [oldPassword, newPassword, confirmPassword]
const showPassword = ref([true, true, true]); // Corresponds to passwords array, true = hidden

// --- Methods ---

// Optional: Validate length on blur (can be removed if only validating on submit)
const validatePasswordLength = (index) => {
  const pwd = passwords.value[index];
  // Only validate new password length strictly on blur if desired
  if (index === 1 && (pwd.length < 6 || pwd.length > 20) && pwd.length > 0) {
    uni.showToast({
      title: "新密码长度应为6-20位",
      icon: "none",
      duration: 2000,
    });
    return false;
  }
  return true;
};

// Toggle password visibility for a specific input
const togglePasswordVisibility = (index) => {
  const currentVisibility = [...showPassword.value];
  currentVisibility[index] = !currentVisibility[index];
  showPassword.value = currentVisibility;
};

// Handle form submission
const handleSubmit = async () => {
  const [oldPwd, newPwd, confirmPwd] = passwords.value;

  // --- Comprehensive Validation ---
  if (!oldPwd) {
    return uni.showToast({ title: "请输入原密码", icon: "none" });
  }
  if (!newPwd) {
    return uni.showToast({ title: "请输入新密码", icon: "none" });
  }
  if (!confirmPwd) {
    return uni.showToast({ title: "请确认新密码", icon: "none" });
  }

  if (newPwd.length < 6 || newPwd.length > 20) {
    return uni.showToast({ title: "新密码长度应为6-20位", icon: "none" });
  }

  if (newPwd !== confirmPwd) {
    return uni.showToast({ title: "两次输入的新密码不一致", icon: "none" });
  }

  if (oldPwd === newPwd) {
    return uni.showToast({ title: "新密码不能与原密码相同", icon: "none" });
  }

  // --- API Call ---
  uni.showLoading({ title: "正在提交...", mask: true });
  try {
    // console.log("Submitting:", { oldPassword: oldPwd, newPassword: newPwd });
    // const res = await sheep.$api.user.updatePassword({
    //   oldPassword: oldPwd,
    //   newPassword: newPwd,
    // });
    const res = await other.thirdPartyCompanyUserUpdatePassword({
      wx_pawd_old: oldPwd,
      wx_pawd_new: newPwd,
      wx_id: sheep.$store("user").userInfo.wx_id,
    });
    // --- Mock Success ---
    await new Promise((resolve) => setTimeout(resolve, 500)); // Simulate network delay
    console.log("修改密码成功 (Mock)");
    uni.hideLoading();
    uni.showToast({ title: "修改成功", icon: "success", duration: 1500 });

    // Optional: Navigate back or to login after success
    // setTimeout(() => {
    //   const pages = getCurrentPages();
    //   if (pages.length > 1) {
    //     uni.navigateBack();
    //   } else {
    //     // If it's the only page, maybe go to home or login
    //     // uni.reLaunch({ url: "/pages/login/login" });
    //   }
    // }, 1500);
  } catch (error) {
    uni.hideLoading();
    console.error("修改密码失败:", error);
    // Use error message from API if available, otherwise generic message
    const errorMsg = error?.msg || error?.message || "修改失败，请重试";
    uni.showToast({ title: errorMsg, icon: "none", duration: 2000 });
  }
};
</script>

<style lang="scss" scoped>
/* Page container styles (similar to target) */
.change-password-page {
  background: #f8f9fa; /* Light gray background */
  min-height: 100vh;
  box-sizing: border-box;
}

.container {
  padding: 30rpx; /* Consistent padding */
  box-sizing: border-box;
}

/* Header styles (from target) */
.header-box {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  .title {
    font-size: 40rpx;
    font-weight: 700;
    color: #1a1a1a;
  }
}

/* Form card styles (from target) */
.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx 20rpx 0 20rpx; /* Adjusted padding to remove bottom padding */
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.1);
}

/* Submit button styles (from target) */
.submit-btn {
  background: linear-gradient(
    135deg,
    #0052d9,
    #2979ff
  ); /* Gradient background */
  border-radius: 50rpx; /* Fully rounded */
  height: 90rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 16rpx rgba(0, 82, 217, 0.3); /* Button shadow */
  transition: background 0.3s ease;

  &:active {
    background: linear-gradient(
      135deg,
      darken(#0052d9, 5%),
      /* Darken on press */ darken(#2979ff, 5%)
    );
  }

  .btn-text {
    color: #fff;
    font-size: 34rpx;
    font-weight: 500;
  }

  /* 新增：固定在底部 */
  position: fixed;
  bottom: 30rpx; /* 距离底部的距离 */
  left: 30rpx; /* 距离左侧的距离 */
  right: 30rpx; /* 距离右侧的距离 */
}
</style>
